package com.britoso;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.SwingWorker;

class SearchManagerForRows extends SwingWorker<Integer, Integer>
{
	private static final int HTTP_CONNECTION_LIMIT = 15;

	@Override
	protected Integer doInBackground() throws Exception
	{
		long start = System.currentTimeMillis();
		MovieInfo.log("Starting search with " + HTTP_CONNECTION_LIMIT + " threads.");
		//Creates a thread pool that reuses a fixed set of threads operating off a shared unbounded queue.
		//If any thread terminates due to a failure during execution prior to shutdown, a new one will
		//take its place if needed to execute subsequent tasks. 
		ExecutorService es = Executors.newFixedThreadPool(HTTP_CONNECTION_LIMIT);
		List<Callable<Object>> todo = new ArrayList<Callable<Object>>(MovieInfo.table.getSelectedRows().length);
		
		
		int[] selectedRows = MovieInfo.table.getSelectedRows();
		if (selectedRows.length > 0)
		{
			for (int i = 0; i < selectedRows.length; i++)
			{
				todo.add(Executors.callable(new SearchThread(MovieInfo.model, MovieInfo.table.convertRowIndexToModel(selectedRows[i]))));
			}
		}
		

		try
		{

			es.invokeAll(todo);
			MovieInfo.log("Search Complete. " + MovieInfo.model.getRowCount() + " searches in " + (System.currentTimeMillis() - start) + "ms.");

		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		return 0;
	}
}